package com.ht.module.common.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dingtalkcontact_1_0.models.GetUserHeaders;
import com.aliyun.dingtalkoauth2_1_0.Client;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.dingtalkoauth2_1_0.models.GetUserTokenRequest;
import com.aliyun.dingtalkoauth2_1_0.models.GetUserTokenResponse;
import com.aliyun.teautil.models.RuntimeOptions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ht.config.properties.DingDingProperties;
import com.ht.module.sys.entity.SysUser;
import com.ht.module.sys.service.ISysUserService;
import com.ht.module.sys.vo.SysUser.UserLoginVo;
import com.ht.util.JsonResult;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @ClassName ThreeCertificationController
 * @Description TODO（钉钉相关接口）
 * @Author hejialun
 * @Date 2022/12/6 16:58
 * @Version 1.0
 */
@RestController
@RequestMapping("/dingding")
@Api(tags = "钉钉相关接口 ")
@Slf4j
public class DingdingController {
    @Resource
    private DingDingProperties dingDingProperties;
    @Resource
    private ISysUserService sysUserService;



    @GetMapping(value = "/login")
    public JsonResult login(@RequestParam(value = "authCode")String authCode) throws Exception {
        log.info("钉钉扫码用户登录进入");
        log.info("回调的code={}",authCode);
        log.info("钉钉配置信息={}",dingDingProperties);
        //定义配置
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        Client client = new Client(config);
        GetUserTokenRequest getUserTokenRequest = new GetUserTokenRequest()
                //应用基础信息-应用信息的AppKey,请务必替换为开发的应用AppKey
                .setClientId(dingDingProperties.getAppKey())

                //应用基础信息-应用信息的AppSecret，,请务必替换为开发的应用AppSecret
                .setClientSecret(dingDingProperties.getAppSecret())
                .setCode(authCode)
                .setGrantType("authorization_code");
        GetUserTokenResponse getUserTokenResponse = client.getUserToken(getUserTokenRequest);
        //获取用户个人token
        String accessToken = getUserTokenResponse.getBody().getAccessToken();

        log.info("accessToken={}",accessToken);

        //获取个人信息

        Config userInfoConfig = new Config();
        config.protocol = "https";
        config.regionId = "central";

        com.aliyun.dingtalkcontact_1_0.Client userInfoClient =new com.aliyun.dingtalkcontact_1_0.Client(userInfoConfig);
        GetUserHeaders getUserHeaders = new GetUserHeaders();
        getUserHeaders.xAcsDingtalkAccessToken = accessToken;
        //获取用户个人信息
        String me = JSON.toJSONString(userInfoClient.getUserWithOptions("me", getUserHeaders, new RuntimeOptions()).getBody());
        log.info("获取钉钉用户信息={}",me);
        //转成json
        JSONObject infoJson = JSONObject.parseObject(me);
        //获取钉钉的unionId
        String unionId = infoJson.getString("unionId");
        //反查询出数据库中关联了当前id的用户
        SysUser sysUser = sysUserService.getOne(
                new QueryWrapper<SysUser>().eq("dd_union_id", unionId)
        );
        //登录当前用户
        UserLoginVo userLoginVo = sysUserService.loginUser(sysUser.getUsername());
        log.info("钉钉扫码登录成功");

        return JsonResult.success(userLoginVo);

    }

}
